import React, { PureComponent, Fragment } from 'react';
import {
  Card,
  Button,
  Row,
  Col,
  Input,
  Icon,
  Radio,
  Form,
  DatePicker,
  message,
  Tooltip,
} from 'antd';
import qs from 'qs';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import moment from 'moment';
import _ from 'lodash';
import { showConfirm } from '@/utils/utils';
import PageEmpty from '@/components/PageEmpty';
import ProjectsPath from '@/components/ProjectsPath';
import styles from '../../index.less';
import * as apis from '@/services/SupplyPlanMgr';
import { BaseTable, utils } from '@/components/BaseTable';
import AuthorizedButton from '@/components/AuthorizedButton';
import HeaderRenderer from '@/components/BaseTable/HeaderRenderer';

const FormItem = Form.Item;

@Form.create()
@connect(state => ({
  items: state.ConfirmProjectItems,
  orgStructure: state.orgStructure,
  Permissions: state.Permissions,
}))
export default class ConfirmProject extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      emptyMsg: '',
      showSupplyConfirm: false,
      confirmMonth: '',
      projectName: '',
      month: '',
      status: '',
      // versionType: this.props.match.params.category,
      headerHeight: [30, 30, 30],
      titleTree: [],
      fixedColumns: [],
      okBtnLoading: false,
    };
  }

  async componentDidMount() {
    // const { match } = this.props;
    const daysInMonth = moment().daysInMonth();
    // days 最后供货确认的天数
    // const days = 2;
    // 是否在当月供货确认之前 是取上个月 否 当前月
    const confirmMonth = moment().format('YYYY-MM');

    // if (
    //   moment().isBefore(
    //     moment()
    //       .date(daysInMonth - days)
    //       .format('YYYY-MM-DD'),
    //   )
    // ) {
    //   confirmMonth = moment()
    //     .subtract(1, 'month')
    //     .format('YYYY-MM');
    // }
    this.setState({
      month: confirmMonth,
      confirmMonth,
    });
    // if (match.params.project) {
    this.getItems(this.props, confirmMonth);
    // }
  }

  componentWillReceiveProps(nextProps) {
    // match变动
    if (
      this.props.match.params.project !== nextProps.match.params.project &&
      nextProps.match.params.project
    ) {
      const { month } = this.state;
      this.getItems(nextProps, month);
    }
  }

  /**
   *
   *
   * @memberof ConfirmProject 是否显示供货确认按钮
   *
   */
  showSupplyConfirm = params => {
    apis.isShowSupplyConfirmUsingGET(params).then(result => {
      if (result) {
        this.setState({
          showSupplyConfirm: result.data,
        });
      }
    });
  };

  /**
   *
   *
   * @memberof ConfirmProject
   */

  renderData = datas => {
    const { project } = this.props.match.params;
    if (!datas.length) {
      this.setState({ emptyMsg: '暂无数据' });
    } else {
      const titleTree = [
        {
          name: '区域/项目/分期',
          key: 'id',
          colspan: 1,
          rowspan: 3,
        },
        {
          name: '确认状态',
          key: 'confirm',
          colspan: 1,
          rowspan: 3,
        },
        {
          name: '确认人',
          key: 'identifyingPeople',
          colspan: 1,
          rowspan: 3,
        },
        {
          name: '确认时间',
          key: 'confirmTime',
          colspan: 1,
          rowspan: 3,
        },
      ];
      const fixedColumns = [
        {
          key: 'name',
          dataKey: 'name',
          width: 250,
          frozen: 'left',
          cellRenderer: ({ rowData }) => (
            <Tooltip placement="topLeft" title={rowData.name}>
              <div
                style={{
                  width: '100%',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                }}
              >
                {rowData.name}
              </div>
            </Tooltip>
          ),
        },
        {
          key: 'confirm',
          dataKey: 'confirmStatus',
          width: 100,
          // frozen: 'left',
          align: 'center',
          cellRenderer: data => {
            if (data.rowData.type === 'org_project') {
              return (
                <Icon
                  type={data.rowData.confirmStatus ? 'check-circle' : 'close-circle'}
                  twoToneColor={data.rowData.confirmStatus ? '#52c41a' : '#e81f29'}
                  theme="twoTone"
                />
              );
            }
            return null;
          },
        },
        {
          key: 'confirmBy',
          dataKey: 'confirmBy',
          width: 100,
          // frozen: 'left',
        },
        {
          key: 'confirmTime',
          dataKey: 'confirmTime',
          width: 130,
          // frozen: 'left',
        },
      ];
      // columns months
      const monthDatas = datas[0].monthData;
      _.forEach(monthDatas, result => {
        titleTree.push({
          name: `${moment(result.month).format('YYYY年MM月')}供货计划`,
          // name: `${moment(this.state.month).year()}年${moment(result.month).month() + 1}供货计划`,
          key: result.month,
          colspan: 4,
          rowspan: 2,
        });
        _.forEach(
          [
            { key: 'num', title: '套数', type: 1, width: 130 },
            { key: 'saleArea', title: '面积', type: 0, width: 100 },
            { key: 'avgPrice', title: '均价', type: 2, width: 130 },
            { key: 'price', title: '金额', type: 3, width: 200 },
          ],
          source => {
            fixedColumns.push({
              key: `${result.month}_${source.key}`,
              width: source.width,
              align: 'right',
              cellRenderer: d => {
                const monthData = _.filter(d.rowData.monthData, { month: result.month });
                if (monthData.length) {
                  return monthData[0][source.key];
                }
              },
              headerRenderer: () => (
                <div>
                  <HeaderRenderer type={source.type}>
                    <div>{source.title}</div>
                  </HeaderRenderer>
                </div>
              ),
            });
          },
        );
      });

      // columns year
      const yearDatas = moment(datas[0].monthData[0].month)
        .format('YYYY')
        .split(',');
      _.forEach(yearDatas, result => {
        titleTree.push({
          name: `${datas[0].year}年年度供货`,
          key: result,
          rowspan: 1,
          children: [
            {
              name: '年度计划供货',
              key: 'ndjhgh',
              colspan: 4,
              rowspan: 1,
            },
            {
              name: '年度实际供货',
              key: 'ndsjgh',
              colspan: 4,
              rowspan: 1,
            },
            {
              name: '达成率',
              key: 'dcl',
              colspan: 1,
              rowspan: 2,
            },
          ],
        });
        // 年度计划供货
        _.forEach(
          [
            { key: 'yearNum', title: '套数', type: 1 },
            { key: 'yearArea', title: '面积', type: 0 },
            { key: 'yearAvgPrice', title: '均价', type: 1 },
            { key: 'yearPrice', title: '金额', type: 1 },
          ],
          source => {
            fixedColumns.push({
              key: `${result}_${source.key}`,
              dataKey: source.key,
              width: 200,
              align: 'right',
              headerRenderer: () => (
                <div>
                  <HeaderRenderer type={source.type}>
                    <div>{source.title}</div>
                  </HeaderRenderer>
                </div>
              ),
            });
          },
        );
        // 年度实际供货
        _.forEach(
          [
            { key: 'yearActualNum', title: '套数', type: 1 },
            { key: 'yearActualArea', title: '面积', type: 0 },
            { key: 'yearActualAveragePrice', title: '均价', type: 2 },
            { key: 'yearActualPrice', title: '金额', type: 3 },
          ],
          source => {
            fixedColumns.push({
              key: `${result}_${source.key}`,
              dataKey: source.key,
              width: 180,
              align: 'right',
              headerRenderer: () => (
                <div>
                  <HeaderRenderer type={source.type}>
                    <div>{source.title}</div>
                  </HeaderRenderer>
                </div>
              ),
            });
          },
        );
        // 达成率
        _.forEach([{ key: 'achievingRate', title: '达成率' }], source => {
          fixedColumns.push({
            key: `${result}_${source.key}`,
            width: 100,
            align: 'right',
            title: source.title,
            cellRenderer: d => {
              if (!d.rowData[source.key]) {
                return '';
              }
              if (d.rowData[source.key] === '-') {
                return '-';
              }
              return `${(d.rowData[source.key] * 100).toFixed(3)}%`;
            },
          });
        });
      });

      // 取消供货
      if (_.includes(this.props.Permissions.buttons, 'button_1040301') && !project) {
        titleTree.push({
          name: '操作',
          key: 'operate',
          colspan: 1,
          marginTop: 3,
          rowspan: 3,
        });
        fixedColumns.push({
          key: 'operate',
          dataKey: 'operate',
          width: 88,
          align: 'right',
          title: '操作',
          frozen: 'right',
          cellRenderer: data => {
            if (data.rowData.type === 'org_project' && data.rowData.confirmStatus) {
              return (
                <div style={{ margin: '0 auto' }}>
                  <AuthorizedButton key="1" authority="business_OkSupply_cancelSupply">
                    <Button
                      type="primary"
                      size="small"
                      onClick={() => {
                        showConfirm(
                          () => this.cancelSupply(data.rowData.id),
                          `取消${data.rowData.name}的供货确认？`,
                          '取消后，项目人员可以重新进行供货确认！',
                        );
                      }}
                    >
                      取消供货
                    </Button>
                  </AuthorizedButton>
                </div>
              );
            }
            return null;
          },
        });
      }

      this.setState({
        titleTree,
        fixedColumns,
      });
    }
  };

  /*
   *数据加载中
   */
  getItems = (props, month, projectName = '') => {
    this.setState({ month, emptyMsg: '版本数据加载中...' });
    const self = this;
    const { dispatch, match } = props;
    const { status } = this.state;
    this.setState({
      projectName,
    });
    // if (match.params.project) {
    // 项目
    const params = {
      id: match.params.project,
      projectName,
      status,
      versionDate: month,
    };
    dispatch({
      type: 'ConfirmProjectItems/init',
      payload: {
        params,
      },
      callback: data => {
        self.setState({ emptyMsg: '' });
        if (match.params.project) {
          self.showSupplyConfirm({
            params: { projectId: match.params.project, versionDate: month },
          });
        }
        self.renderData(data);
      },
    });
  };

  /**
   *
   *
   * @memberof ConfirmProject 供货确认
   */
  supplyConfirm = () => {
    this.setState({
      okBtnLoading: true,
    });
    const { project } = this.props.match.params;
    const { month } = this.state;
    const params = {
      projectId: project,
      versionDate: month,
    };
    apis.supplyConfirmUsingPUT({ params }).then(result => {
      if (!_.isNull(result.data)) {
        message.success('供货确认成功');
        this.getItems(this.props, month);
        this.setState({
          showSupplyConfirm: false,
          okBtnLoading: false,
        });
      } else {
        this.setState({
          okBtnLoading: false,
        });
      }
    });
  };

  /**
   *
   *
   * @memberof ConfirmProject
   */
  cancelSupply(projectId) {
    const { month } = this.state;
    const params = {
      projectId,
      versionDate: month,
    };
    apis.cancelSupplyConfirmUsingPUT({ params }).then(result => {
      if (result.data) {
        this.getItems(this.props, month);
      }
    });
  }

  render() {
    const {
      fixedColumns,
      headerHeight,
      emptyMsg,
      titleTree,
      month,
      confirmMonth,
      showSupplyConfirm,
      status,
      projectName,
      okBtnLoading,
    } = this.state;
    const treeData = this.props.items.searched;
    const { expandedRowKeys } = this.props.items;
    const { orgStructure } = this.props;
    const headerRenderer = utils.getHeaderRenderer(titleTree, 2);
    const { project } = this.props.match.params;
    const { getFieldDecorator } = this.props.form;
    let projectOrgName = '';
    if (orgStructure && orgStructure.data && orgStructure.data.length && project) {
      projectOrgName = _.filter(orgStructure.data, { orgdepid: project })[0].orgname;
    }
    // 导出报表
    const params = {
      projectName: project && treeData.length > 0 ? treeData[0].name : '',
      status: project && treeData.length > 0 ? treeData[0].confirmStatus : '',
      versionDate: month,
    };
    const sessionToken = localStorage.getItem('sessionToken');
    const exportQueryString = qs.stringify({ ...params, sessionToken });
    // 导出报表 --- end
    return (
      <PageHeaderWrapper
        breadcrumb={null}
        title={
          project ? (
            <ProjectsPath menu="ConfirmProject" {...this.props} />
          ) : (
            <span style={{ fontSize: '14px', fontWeight: '500', color: '#333333' }}>旭辉集团</span>
          )
        }
        extra={[
          <div className="header-btns">
            供货月份：
            <DatePicker.MonthPicker
              allowClear={false}
              disabledDate={date => {
                if (moment(confirmMonth).isBefore(moment(date).format('YYYY-MM'))) {
                  return true;
                }
                return false;
              }}
              onChange={(field, value) => {
                this.setState({
                  month: value,
                });
                if (value) {
                  this.getItems(this.props, value);
                }
              }}
              value={month ? moment(month, 'YYYY-MM') : ''}
              format="YYYY-MM"
            />
            {project ? (
              <></>
            ) : (
              <AuthorizedButton key="1" authority="supply_overall_Export">
                {treeData && treeData.length > 0 ? (
                  <Button
                    style={{ marginLeft: '5px' }}
                    className="yellow-button"
                    target="_blank"
                    href={`${process.env.apiUrl}/api/v1/supplyPlan/supplyConfirmExport?${exportQueryString}`}
                  >
                    导出报表
                  </Button>
                ) : null}
              </AuthorizedButton>
            )}
          </div>,
        ]}
      >
        <Card>
          <div className={styles.container}>
            <div>
              <Row type="flex" align="middle" justify="space-between">
                <Col style={{ fontSize: '16px', fontWeight: '500', color: '#333333' }}>
                  供货确认表
                </Col>
                <Col md={14} style={{ textAlign: 'right' }}>
                  {!project ? (
                    <Form layout="inline">
                      <Row type="flex" align="middle" justify="end">
                        <Col md={24} sm={24}>
                          <FormItem label="">
                            <span style={{ marginRight: '10px' }}>确认状态:</span>
                            <Radio.Group
                              onChange={e => {
                                this.setState(
                                  {
                                    status: e.target.value,
                                  },
                                  () => {
                                    this.getItems(this.props, month);
                                  },
                                );
                              }}
                              value={status}
                            >
                              <Radio value="">全部</Radio>
                              <Radio value={1}>已确认</Radio>
                              <Radio value={0}>未确认</Radio>
                            </Radio.Group>
                          </FormItem>
                          <FormItem label="">
                            {getFieldDecorator('projectName', {
                              initialValue: projectName,
                            })(
                              <Input
                                allowClear
                                onPressEnter={() => {
                                  const { form } = this.props;
                                  form.validateFields((err, fieldsValue) => {
                                    if (err) return;
                                    this.getItems(this.props, month, fieldsValue.projectName);
                                  });
                                }}
                                onChange={e => {
                                  if (!e.target.value) {
                                    this.getItems(this.props, month);
                                  }
                                }}
                                placeholder="请输入项目名称"
                              />,
                            )}
                          </FormItem>
                        </Col>
                      </Row>
                    </Form>
                  ) : null}
                </Col>
                {showSupplyConfirm && project && treeData.length ? (
                  <Col>
                    <AuthorizedButton authority="supply_overall_OkSupply">
                      <Button
                        loading={okBtnLoading}
                        type="primary"
                        onClick={() => {
                          showConfirm(
                            () => this.supplyConfirm(),
                            `确认${projectOrgName}项目${moment(month)
                              .add(1, 'months')
                              .format('YYYY年MM月')}供货`,
                            '确认后营销将基于确认的供货计划编制签约计划！',
                          );
                        }}
                      >
                        确认供货
                      </Button>
                    </AuthorizedButton>
                  </Col>
                ) : null}
              </Row>
            </div>
            {treeData.length > 0 ? (
              <Fragment>
                <BaseTable
                  subtractHeight="180px"
                  defaultExpandedRowKeys={expandedRowKeys}
                  expandColumnKey="name"
                  fixedColumns={fixedColumns}
                  headerHeight={headerHeight}
                  headerRenderer={headerRenderer}
                  treeData={treeData}
                />
              </Fragment>
            ) : (
              <PageEmpty emptyTitle={emptyMsg} />
            )}
          </div>
        </Card>
      </PageHeaderWrapper>
    );
  }
}
